<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户编码" prop="customerCode">
        <el-input
          v-model="queryParams.customerCode"
          placeholder="请输入客户编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户类型" prop="customerType">
        <el-select v-model="queryParams.customerType" placeholder="请选择客户类型" clearable>
          <el-option
            v-for="dict in dict.type.sys_customer_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="客户状态" clearable>
          <el-option key="0" label="正常" value="0" />
          <el-option key="1" label="停用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['test:customer:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['test:customer:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['test:customer:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['test:customer:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['test:customer:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="customerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column label="客户编码" align="left" prop="customerCode" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="客户名称" align="left" prop="customerName" :show-overflow-tooltip="true" min-width="200" />
      <el-table-column label="所在地区" align="left" :show-overflow-tooltip="true" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.province }} {{ scope.row.city }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所在行业" align="left" prop="industryType" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_industry_type" :value="scope.row.industryType"/>
        </template>
      </el-table-column>
      <el-table-column label="客户类型" align="center" prop="customerType" width="90">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_customer_type" :value="scope.row.customerType"/>
        </template>
      </el-table-column>
      <el-table-column label="信用等级" align="center" prop="creditLevel" width="90">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_credit_level" :value="scope.row.creditLevel"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['test:customer:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['test:customer:edit']"
          >修改</el-button>

        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改客户信息对话框 -->
    <el-drawer
      :title="title"
      :visible.sync="open"
      direction="rtl"
      size="67%"
      :before-close="cancel"
    >
      <div style="padding: 0 20px;">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="客户名称" prop="customerName">
                <el-input v-model="form.customerName" placeholder="请输入客户名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户编码" prop="customerCode">
                <el-input v-model="form.customerCode" placeholder="请输入客户编码" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="所在地区" prop="province">
                <region-select
                  :province.sync="form.province"
                  :city.sync="form.city"
                  placeholder="请选择所在地区"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户类型" prop="customerType">
                <el-select v-model="form.customerType" placeholder="请选择客户类型">
                  <el-option
                    v-for="dict in dict.type.sys_customer_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="所在行业" prop="industryType">
                <el-select v-model="form.industryType" placeholder="请选择所在行业">
                  <el-option
                    v-for="dict in dict.type.sys_industry_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="信用等级" prop="creditLevel">
                <el-select v-model="form.creditLevel" placeholder="请选择信用等级">
                  <el-option
                    v-for="dict in dict.type.sys_credit_level"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="公司网站" prop="website">
                <el-input v-model="form.website" placeholder="请输入公司网站" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户状态" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio key="0" label="0">正常</el-radio>
                  <el-radio key="1" label="1">停用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="详细地址" prop="address">
                <el-input v-model="form.address" type="textarea" placeholder="请输入详细地址" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="客户描述" prop="description">
                <el-input v-model="form.description" type="textarea" placeholder="请输入客户描述" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style="padding: 20px 0 0 100px;">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 客户详情对话框 -->
    <el-drawer
      title="客户详情"
      :visible.sync="detailOpen"
      direction="rtl"
      size="67%"
    >
      <div style="padding: 0 20px 20px 20px;">
        <el-descriptions class="margin-top" :column="2" border>
          <el-descriptions-item label="客户名称">{{ detailForm.customerName }}</el-descriptions-item>
          <el-descriptions-item label="客户编码">{{ detailForm.customerCode }}</el-descriptions-item>
          <el-descriptions-item label="所在省份">{{ detailForm.province }}</el-descriptions-item>
          <el-descriptions-item label="所在城市">{{ detailForm.city }}</el-descriptions-item>
          <el-descriptions-item label="所在行业">
            <dict-tag :options="dict.type.sys_industry_type" :value="detailForm.industryType"/>
          </el-descriptions-item>
          <el-descriptions-item label="客户类型">
            <dict-tag :options="dict.type.sys_customer_type" :value="detailForm.customerType"/>
          </el-descriptions-item>
          <el-descriptions-item label="信用等级">
            <dict-tag :options="dict.type.sys_credit_level" :value="detailForm.creditLevel"/>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="detailForm.status === '0' ? 'success' : 'danger'">
              {{ detailForm.status === '0' ? '正常' : '停用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="公司网站" :span="2">
            <el-link v-if="detailForm.website" :href="detailForm.website" target="_blank" type="primary">
              {{ detailForm.website }}
            </el-link>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="详细地址" :span="2">{{ detailForm.address || '-' }}</el-descriptions-item>
          <el-descriptions-item label="客户描述" :span="2">{{ detailForm.description || '-' }}</el-descriptions-item>
          <el-descriptions-item label="创建者">{{ detailForm.createBy }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ detailForm.createTime }}</el-descriptions-item>
          <el-descriptions-item label="更新者">{{ detailForm.updateBy || '-' }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ detailForm.updateTime || '-' }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ detailForm.remark || '-' }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-drawer>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的客户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCustomer, getCustomer, delCustomer, addCustomer, updateCustomer } from "@/api/test/customer";
import RegionSelect from "@/components/RegionSelect";
import { getToken } from "@/utils/auth";

export default {
  name: "Customer",
  dicts: ['sys_industry_type', 'sys_customer_type', 'sys_credit_level'],
  components: {
    RegionSelect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户信息表格数据
      customerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      detailOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerName: null,
        customerCode: null,
        customerType: null,
        status: null
      },
      // 表单参数
      form: {},
      // 详情表单参数
      detailForm: {},
      // 表单校验
      rules: {
        customerName: [
          { required: true, message: "客户名称不能为空", trigger: "blur" },
          { max: 100, message: "客户名称不能超过100个字符", trigger: "blur" }
        ],
        customerCode: [
          { required: true, message: "客户编码不能为空", trigger: "blur" },
          { max: 50, message: "客户编码不能超过50个字符", trigger: "blur" }
        ],
        province: [
          { max: 50, message: "所在省份不能超过50个字符", trigger: "blur" }
        ],
        city: [
          { max: 50, message: "所在城市不能超过50个字符", trigger: "blur" }
        ],
        industryType: [
          { max: 50, message: "所在行业不能超过50个字符", trigger: "blur" }
        ]
      },
      // 上传参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的客户数据
        updateSupport: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/test/customer/importData"
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询客户信息列表 */
    getList() {
      this.loading = true;
      listCustomer(this.queryParams).then(response => {
        this.customerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        customerId: null,
        customerName: null,
        customerCode: null,
        province: null,
        city: null,
        industryType: null,
        address: null,
        website: null,
        description: null,
        creditLevel: "1",
        customerType: "1",
        status: "0",
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.customerId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加客户信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const customerId = row.customerId || this.ids
      getCustomer(customerId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改客户信息";
      });
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      const customerId = row.customerId;
      getCustomer(customerId).then(response => {
        this.detailForm = response.data;
        this.detailOpen = true;
      });
    },
    /** 客户状态修改 */
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.customerName + '"客户吗？').then(function() {
        return updateCustomer(row);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.customerId != null) {
            updateCustomer(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCustomer(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const customerIds = row.customerId || this.ids;
      this.$modal.confirm('是否确认删除客户信息编号为"' + customerIds + '"的数据项？').then(function() {
        return delCustomer(customerIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('test/customer/export', {
        ...this.queryParams
      }, `customer_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "客户数据导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('/test/customer/importTemplate', {}, `customer_template_${new Date().getTime()}.xlsx`);
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>

<style scoped>
.el-upload__tip {
  line-height: 20px;
  margin-top: 7px;
  color: #666;
}
</style>